﻿using Autofac;

 
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using WebMvc.Models;
using Microsoft.AspNet.Identity;
using System.Web.Mvc;

namespace WebMvc
{
    public class IoC : ContainerBuilder
    {
        /// <summary>
        /// 
        /// </summary>
        private readonly static IoC _instance = new IoC();

        /// <summary>
        /// 
        /// </summary>
        private static object _lock;

        /// <summary>
        /// 
        /// </summary>
        private IContainer _componentsContainer;

        /// <summary>
        /// 
        /// </summary>
        public static IoC Instance
        {
            get
            {
                return _instance;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public IContainer GetComponentsContainer()
        {
            if (_componentsContainer == null)
            {
                lock (_lock)
                {
                    if (_componentsContainer == null)
                        _componentsContainer = this.Build();
                }
            }

            return _componentsContainer;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public T Resolve<T>() where T : class
        {
            return GetComponentsContainer().Resolve<T>();
        } 

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public ILifetimeScope BeginLifetimeScope()
        {
            return GetComponentsContainer().BeginLifetimeScope();
        }

        /// <summary>
        /// 
        /// </summary>
        private IoC()
        {
            _lock = new object();
            //ConfigureDependencies();
        }

        /// <summary>
        /// 
        /// </summary>
        private void ConfigureDependencies()
        {
            //Configure all your depedendencies here!!

            //控制器
            this.RegisterType<CustomControllerActivator>().As<IControllerActivator>().InstancePerLifetimeScope();

            //Database connection
            var connectionString = ConfigurationManager.ConnectionStrings["Default"].ConnectionString;
            this.Register(c => new SqlConnection(connectionString)).As<IDbConnection>().InstancePerLifetimeScope();

             
        }
    }
}